class SuperTask {
  public parallelCount: number;
  public tasks: any[];
  public runningCount: number;
  constructor(parallelCount = 2) {
    this.parallelCount = parallelCount;
    this.tasks = [];
    this.runningCount = 0;
  }
  add(task) {
    return new Promise((resolve, reject) => {
      this.tasks.push({ task, resolve, reject });
      this._run();
    });
  }
  _run() {
    if (this.tasks.length && this.runningCount < this.parallelCount) {
      this.runningCount++;
      const { task, resolve, reject } = this.tasks.shift();
      task()
        .then(resolve)
        .catch(reject)
        .finally((res) => {
          this.runningCount--;
          this._run();
        });
    }
  }
}

function timeout(time) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(1);
    }, time);
  });
}
const superTask = new SuperTask(2);
function addTask(time, name) {
  superTask
    .add(() => timeout(time))
    .then(() => {
      console.log(`任务${name}完成`);
    });
}
addTask(10000, 1); // 10000 1
addTask(5000, 2); // 5000 2
addTask(3000, 3); // 8000 3
addTask(4000, 4); // 12000 4
addTask(5000, 5); // 15000 5
